<template>
  <div class="login">
    <div class="left"></div>
    <div class="loginContain">
      <h1 class="title">
        <span
          :class="['jiaobiao', 'iconfont',isWechat?'icon-diannaojiaobiao':'icon-erweimajiaobiao']"
          @click="checkoutLoginType"
        ></span>BACKSTAGE
      </h1>
      <transition>
        <!--二维码-->
        <div v-if="isWechat" class="wechatLogin">
          <div class="scancode">
            <div class="marsk" v-if="isScan">
              <i class="iconfont icon-saomachenggong"></i>
            </div>
            <img src="../assets/erwei.png" alt width="200" />
          </div>
        </div>
        <!--登录表单-->
        <el-form
          v-else
          ref="loginForm"
          :model="loginForm"
          label-width="80px"
          :rules="loginRules"
          status-icon
        >
          <el-form-item prop="username">
            <el-input
              type="text"
              v-model="loginForm.username"
              prefix-icon="el-icon-user"
              autocomplete="off"
              autofocus
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              prefix-icon="el-icon-lock"
              autocomplete="off"
              @keypress.native.enter="submitForm"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">登录</el-button>
            <el-button class="chongzhi" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </transition>
    </div>
  </div>
</template>

<script>
import io from 'socket.io-client'
export default {
  data () {
    // 用户名的校验正则
    var validateUsername = (rule, value, callback) => {
      const uPattern = /[a-zA-Z0-9_]{3,16}/
      if (uPattern.test(value)) {
        callback()
      }
      callback(new Error('用户名最短3个字符最长不超过16个字符'))
    }
    // 密码的校验正则
    var validatePassword = (rule, value, callback) => {
      const pPattern = /^[\w_-]{3,16}$/
      if (pPattern.test(value)) {
        callback()
      }
      callback(new Error('密码最短3位，最长16位'))
    }
    return {
      // 表单的数据，用户名和密码
      loginForm: {
        username: '',
        password: ''
      },
      // 表单校验规则
      loginRules: {
        // 用户名
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateUsername, trigger: 'blur' }
        ],
        // 密码
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ]
      },
      // 登录方式的数据
      isWechat: false,
      isScan: false
    }
  },
  methods: {
    // 提交表单方法
    submitForm () {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          // 本地校验通过
          // 打开加载框
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          // 发送登录请求
          const { data: res } = await this.$http.post(
            '/users/login',
            this.loginForm
          )
          // 关闭加载框
          loading.close()
          if (res.status == 1) {
            this.$notify({
              title: '登录成功',
              type: 'success'
            })
            // 登录成功存储token
            console.log(res.permission.buttons)
            const nickname = res.userInfo.username
            const permissionButtons = res.permission.buttons
            window.sessionStorage.setItem('nickname', nickname)
            window.sessionStorage.setItem(
              'permissionButtons',
              permissionButtons
            )
            localStorage.setItem('token', res.token)
            this.$router.push('/welcome')
          } else {
            this.$notify({
              title: '账号或密码错误',
              type: 'warning'
            })
          }
        } else {
          this.$notify({
            title: '登录失败',
            type: 'warning'
          })
          return false
        }
      })
    },
    // 重置按钮
    resetForm () {
      this.$refs.loginForm.resetFields()
    },
    // 登录方式切换
    checkoutLoginType () {
      this.isWechat = !this.isWechat
      if (this.isWechat) {
        // 说明是微信登录
        // 通过socket.io和服务器建立socket连接
        const socket = io('ws://chst.vip')
        const _this = this
        const r = fetch('/api/users/getScancode')
          .then((body) => body.json())
          .then((res) => {}) // 展示二维码
        socket.on('connect', function () {
          console.log('连接成功')
          socket.on('scancodeSuccess', async data => {
            console.log(data)
            console.log(this.isScan)
            if (data.state) {
              _this.isScan = true
              const wechatCode = data.wechatCode
              const { data: res } = await _this.$http.get(
                `/users/wechatLogin?wechatCode=${wechatCode}`
              )
              if (res && res.state) {
              }
              console.log(res.token)
              if (data.state) {
                localStorage.setItem('token', res.token)
                window.sessionStorage.setItem(
                  'nickname',
                  JSON.stringify(res.userInfo.nickname)
                )
                window.sessionStorage.setItem(
                  'permissionButtons',
                  JSON.stringify(res.permission.buttons)
                )
                _this.$router.push('/Welcome')
              }
            }
          })
        })
        socket.on('getScancode', (data) => {
          // 切换成功微信登入事件 可以获得二维码
          console.log(data)
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.v-enter,
.v-leave-to {
  opacity: 0;
}
.v-enter-to,
.v-leave {
  opacity: 1;
}
.v-enter-active,
.v-leave-active {
  transition: all 1s;
}
.login {
  height: 100%;
  width: 100%;
  background: #fff8dc;
  overflow: hidden;
}
.loginContain {
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -200px 0 0 -200px;
  width: 500px;
  height: 350px;
  background: #fff;
}
.el-form {
  width: 100%;
  margin-top: 50px;
  position: absolute;
}
.el-form-item {
}
.el-input {
  margin-left: -10%;
}

.left {
  width: 100%;
  height: 100%;
  background-image: linear-gradient(-90deg, #29bdd9 0%, #9d14e4 100%);
  background-repeat: no-repeat;
  background-size: 100%;
  position: absolute;
  background-position: 60% 65%;
}
.title {
  height: 80px;
  line-height: 80px;
  font-size: 32px;
  font-family: "Microsoft Yahei";
  font-weight: 200;
  color: #fff;
  background: linear-gradient(to top right, #3574dc, #9d14e4);
  padding-left: 10px;
  span {
    line-height: 60px;
    font-size: 40px;
    float: right;
    margin: 10px;
  }
}
.wechatLogin {
  width: 100%;
  position: absolute;
  text-align: center;
  height: 270px;
  padding-top: 30px;
}
.el-button {
  width: 45%;
  margin: -40px;
}
.chongzhi {
  margin-left: 80px !important;
}
.scancode {
  position: relative;
  height: 220px;
}
.wechatLogin {
  width: 100%;
  text-align: center;
  position: absolute;
  color: #fff;
  .marsk {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 25%;
    z-index: 1;
    background-color: rgba(255, 255, 255, 0.9);
  }
  img {
    position: absolute;
    left: 25%;
  }
  p {
    text-align: center;
  }
}
  i.icon-saomachenggong {
    font-size: 50px;
    color: #26c28f;
    line-height: 200px;
  }
</style>
